package com.dingding.service.activity.universal.core.biz.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.daox.IBaseDaoX;
import com.dingding.common.core.base.daox.ICriteriaBaseDao;
import com.dingding.common.core.beans.UserLogin;
import com.dingding.common.core.beans.share.ActivityGift;
import com.dingding.common.core.beans.share.ActivityShare;
import com.dingding.common.core.exception.bussiness.BizExpEnum;
import com.dingding.common.core.exception.bussiness.BussinessException;
import com.dingding.common.core.url.activity.ActivityUrlFactory;
import com.dingding.facade.user.service.IUserInfoFacade;
import com.dingding.facde.activity.dto.commonactivity.ActivityDetail;
import com.dingding.facde.activity.dto.commonactivity.GiftInfo;
import com.dingding.facde.activity.dto.commonactivity.ReqGetActivityIndex;
import com.dingding.facde.activity.dto.commonactivity.ReqGetInviteInfo;
import com.dingding.facde.activity.dto.commonactivity.ReqRegFromActivity;
import com.dingding.facde.activity.dto.commonactivity.ReqStartAnActivity;
import com.dingding.facde.activity.dto.commonactivity.ReqStartToRegIndex;
import com.dingding.facde.activity.dto.commonactivity.ResGetActivityIndex;
import com.dingding.facde.activity.dto.commonactivity.ResGetInviteInfo;
import com.dingding.facde.activity.dto.commonactivity.ResRegFromActivity;
import com.dingding.facde.activity.dto.commonactivity.ResStartAnActivity;
import com.dingding.facde.activity.dto.commonactivity.ResStartToRegIndex;
import com.dingding.service.activity.universal.core.biz.ICommonActivityService;
import com.dingding.service.share.dao.IActivityShareDao;

/**
 * @Description:通用活动分享的接口
 * @author fengshuonan
 * @date 2016年9月20日 下午3:34:55
 * @version 叮叮搭车
 * @since 2.4
 */
@Component("commonActivityService")
public class CommonActivityServiceImpl implements ICommonActivityService {

	@Resource(name = "activityShareDao")
	private IActivityShareDao activityShareDao;

	@Resource(name = "baseDaoX")
	private IBaseDaoX baseDaoX;

	@Resource(name = "userInfoFacade")
	private IUserInfoFacade userInfoFacade;

	@Resource(name = "criteriaBaseDao")
	private ICriteriaBaseDao criteriaBaseDao;

	/**
	 * @Description:获取活动首页的详细信息接口
	 * @author fengshuonan
	 * @since 2.4
	 */
	@Override
	@Transactional(readOnly = true)
	public ResGetActivityIndex getActivityIndexInfo(ReqGetActivityIndex reqGetActivityIndex) {

		ResGetActivityIndex resGetActivityIndex = new ResGetActivityIndex();

		// 获取分享活动的首页详情
		ActivityDetail activityInfo = this.activityShareDao.getActivityInfo(reqGetActivityIndex.getActivityId());
		BeanUtils.copyProperties(activityInfo, resGetActivityIndex);

		// 获取该活动的所有礼品集合
		List<GiftInfo> giftInfos = this.activityShareDao.getActivityGifts(reqGetActivityIndex.getActivityId());
		resGetActivityIndex.setGiftList(giftInfos);

		return resGetActivityIndex;
	}

	/**
	 * @Description:发起活动
	 * @author fengshuonan
	 * @since 2.4
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public ResStartAnActivity startAnActivity(ReqStartAnActivity reqStartAnActivity) {
		ResStartAnActivity resStartAnActivity = new ResStartAnActivity();
		resStartAnActivity.setWechatTitle("【快抢】有了这支高能战术救生笔，开车胜带n个保镖哇！"); // TODO
																			// 微信分享的标题暂时写死
		resStartAnActivity.setWechatDesc("【快抢】有了这支高能战术救生笔，开车胜带n个保镖哇！"); // TODO
																		// 微信分享的介绍暂时写死

		// 判断用户是否发起过活动
		ActivityShare oldActShare = this.activityShareDao.getUserActivityShare(reqStartAnActivity.getUserId(),
				reqStartAnActivity.getActivityId());

		// 如果用户发起过活动，拼接url的时候用旧的shareKey
		if (oldActShare != null) {
			resStartAnActivity.setShareUrl(
					new ActivityUrlFactory().createActivityShareUrl(oldActShare.getAcId(), oldActShare.getAsId()));

			// 如果用户没发起过活动
		} else {
			ActivityShare newShare = this.activityShareDao.addUsesActivityShare(reqStartAnActivity.getActivityId(),
					reqStartAnActivity.getUserId(), reqStartAnActivity.getGiftId());
			resStartAnActivity.setShareUrl(
					new ActivityUrlFactory().createActivityShareUrl(newShare.getAcId(), newShare.getAsId()));
		}

		return resStartAnActivity;
	}

	/**
	 * @Description:是否发起过某个活动
	 * @param userId
	 *            用户id
	 * @param activityId
	 *            活动id
	 * @author fengshuonan
	 * @return Boolean true 发起过 false 没发起过
	 * @since 2.4
	 */
	@Override
	@Transactional(readOnly = true)
	public Boolean isStartedAnActivity(String userId, String activityId) {

		// 验证这个用户是否存在
		UserLogin ul = this.activityShareDao.getUserlogin(userId);
		if (ul == null) {
			throw new BussinessException(BizExpEnum.NO_THIS_USER);// 查询不到这个用户
		}

		ActivityShare oldActShare = this.activityShareDao.getUserActivityShare(userId, activityId);
		if (oldActShare == null) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * @Description:获取已发起活动的用户的邀请详情
	 * @author fengshuonan
	 * @since 2.4
	 */
	@Override
	@Transactional(readOnly = true)
	public ResGetInviteInfo getInviteInfo(ReqGetInviteInfo reqGetInviteInfo) {
		ResGetInviteInfo resGetInviteInfo = new ResGetInviteInfo();

		// 获取活动详情
		ActivityDetail activityDetail = this.activityShareDao.getActivityInfo(reqGetInviteInfo.getActivityId());
		BeanUtils.copyProperties(activityDetail, resGetInviteInfo);// 设置活动规则详情

		// 获取用户发起的活动的详情
		ActivityShare activityShare = this.activityShareDao.getUserActivityShare(reqGetInviteInfo.getUserId(),
				reqGetInviteInfo.getActivityId());
		if (activityShare == null) {
			throw new BussinessException(BizExpEnum.NO_USER_ACTIVITYSHARE);// 没有该用户的活动分享记录
		}
		resGetInviteInfo.setInviteNum(activityShare.getInviteNum());// 设置邀请人数

		// 获取该活动的达标数量，并判断该用户是否达标
		int reachNum = this.activityShareDao.getActivityReachNum(reqGetInviteInfo.getActivityId());
		resGetInviteInfo.setEnoughNum(reachNum); // 设置该活动的达标数量
		if (activityShare.getInviteNum() < reachNum) {
			resGetInviteInfo.setInviteEnough(false); // 设置该用户是否邀请达标
		} else {
			resGetInviteInfo.setInviteEnough(true);
		}

		// 获取该用户的所选礼品的名称
		ActivityGift gift = this.activityShareDao.getUserActivityGiftName(activityShare.getAsId());
		resGetInviteInfo.setGiftName(gift.getGiftName()); // 设置相应礼物的名称
		resGetInviteInfo.setGiftId(gift.getGiftId()); // 设置相应礼物的id

		// 如果当前用户达标，则返回用户的排名
		if (activityShare.getInviteNum() >= reachNum) {
			int sort = this.activityShareDao.getTheNumSort(reqGetInviteInfo.getActivityId(),
					activityShare.getInviteNum());
			resGetInviteInfo.setSort(sort); // 设置用户发起活动邀请人数的排名
		}

		return resGetInviteInfo;
	}

	/**
	 * @Description:活动注册
	 * @author fengshuonan
	 * @since 2.4
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public ResRegFromActivity regFromActivity(ReqRegFromActivity reqRegFromActivity) {
		ResRegFromActivity resRegFromActivity = new ResRegFromActivity();

		// 验证手机号验证码是否正确
		boolean codeFlag = this.activityShareDao.isMsgCodeTrue(reqRegFromActivity.getTelephone(),
				reqRegFromActivity.getPhoneCode());
		if (codeFlag == false) {
			throw new BussinessException(BizExpEnum.WRONG_PHONE_CODE);
		}

		// 验证sharekey是否存在（用户发起活动的唯一标识asId）
		ActivityShare activityShare = this.baseDaoX.getById(reqRegFromActivity.getShareKey(), ActivityShare.class);
		if (activityShare == null) {
			throw new BussinessException(BizExpEnum.SHARE_KEY_ERROR);
		}

		// 判断手机号是否注册过
		String loginId = this.activityShareDao.isUserHaveReg(reqRegFromActivity.getTelephone());

		// 如果注册过,判断有没有参加过这次唐山开城活动，参加过就略过，没参加过就给发起的司机邀请人数加一
		if (loginId != null) {

			resRegFromActivity.setUserId(loginId);

			// 判断是否参加过这次唐山开城活动
			boolean haveJoinTangshanKaiCheng = this.activityShareDao.haveJoinTangshanKaiCheng(loginId);

			// 如果没有参加过唐山开城活动
			if (!haveJoinTangshanKaiCheng) {

				// 添加被邀请人的记录
				this.activityShareDao.addInviteRecord(reqRegFromActivity.getShareKey(), loginId);

				// 给该发起活动的人添加一次邀请人数
				this.activityShareDao.addActAnsInviteNum(reqRegFromActivity.getShareKey());

				resRegFromActivity.setUserType(2);// 2是提示成功领取到优惠券
				return resRegFromActivity;

			} else {
				resRegFromActivity.setUserType(3);// 3是提示用户重复领取，不能领取
				return resRegFromActivity;
			}

		} else {
			UserLogin addUser = null;
			try {
				addUser = this.userInfoFacade.addUserByWechat(reqRegFromActivity.getTelephone(),
						"This is a null openId!!!");
			} catch (Exception e) {
				throw new BussinessException(BizExpEnum.ADD_USER_ERROR);
			}

			if (addUser == null) {
				throw new BussinessException(BizExpEnum.ADD_USER_ERROR);
			} else {
				resRegFromActivity.setUserId(addUser.getUid());

				// 添加被邀请人的记录
				this.activityShareDao.addInviteRecord(reqRegFromActivity.getShareKey(), addUser.getUid());

				// 给该发起活动的人添加一次邀请人数
				this.activityShareDao.addActAnsInviteNum(reqRegFromActivity.getShareKey());

				resRegFromActivity.setUserType(2); // 2是提示成功领取到优惠券
				return resRegFromActivity;
			}
		}
	}

	/**
	 * @Description:跳转到注册主页的逻辑
	 * @author fengshuonan
	 * @since 2.4
	 */
	@Override
	@Transactional(readOnly = true)
	public ResStartToRegIndex startToRegIndex(ReqStartToRegIndex reqStartToRegIndex) {
		ResStartToRegIndex resStartToRegIndex = new ResStartToRegIndex();

		// 获取首页详情
		ActivityDetail activityInfo = this.activityShareDao.getActivityInfo(reqStartToRegIndex.getActivityId());
		BeanUtils.copyProperties(activityInfo, resStartToRegIndex);

		// 判断openId是否存在于数据库中
		String userId = this.activityShareDao.haveOpenId(reqStartToRegIndex.getOpenId());
		if (userId == null) {
			resStartToRegIndex.setUserType(1); // 没有该用户的信息
		} else {
			resStartToRegIndex.setUserId(userId); // 设置用户的id

			// 如果有这个用户的openId信息，则判断此用户是否发起过活动
			ActivityShare userActivityShare = this.activityShareDao.getUserActivityShare(userId,
					reqStartToRegIndex.getActivityId());
			if (userActivityShare == null) { // 没发起过活动
				resStartToRegIndex.setUserType(2); // 设置类型为老用户没发起过活动
			} else {

				// 如果这个用户发起过活动
				resStartToRegIndex.setUserType(3); // 设置类型为老用户,并且发起过活动
				ResGetInviteInfo inviteInfo = this
						.getInviteInfo(new ReqGetInviteInfo(userId, reqStartToRegIndex.getActivityId()));
				BeanUtils.copyProperties(inviteInfo, resStartToRegIndex); // 设置规则详情，邀请人数，排名，礼品名称
			}
		}
		return resStartToRegIndex;
	}

	/**
	 * @Description:发送短信验证码
	 * @author fengshuonan
	 * @since 2.4
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean sendPhoneMsg(String telephone) {
		return this.activityShareDao.sendPhoneMessage(telephone);
	}

	/**
	 * @Description:判断openId是否存在于数据库
	 * @author fengshuonan
	 * @since 2.4
	 */
	@Override
	public boolean isOpenIdInDb(String openId) {
		return this.activityShareDao.isOpenIdHaveReg(openId);
	}

	/**
	 * @Description:验证手机号验证码是否正确
	 * @author fengshuonan
	 * @since 2.4
	 */
	@Override
	public boolean validateTeleCode(String telephone, String code) {
		return this.activityShareDao.isMsgCodeTrue(telephone, code);
	}

	/**
	 * @Description:通过电话号获取用户登录信息
	 * @author fengshuonan
	 * @since 2.4
	 */
	@Override
	@Transactional(readOnly = true)
	public UserLogin getUserLoginByTele(String telephone) {
		UserLogin userLogin = this.criteriaBaseDao.queryCriteriaListUnique(UserLogin.class,
				Restrictions.eq("userName", telephone));
		if (userLogin == null) {
			return null;
		} else {
			return userLogin;
		}
	}

	/**
	 * @Description:活动注册（来源于优惠券活动）
	 * @author fengshuonan
	 * @since 2.4
	 */
	@Override
	public ResRegFromActivity regFromCoupon(ReqRegFromActivity reqRegFromActivity) {
		return this.regFromActivity(reqRegFromActivity);
	}

	/**
	 * @Description:领取优惠券
	 * @author fengshuonan
	 * @since 2.4
	 */
	@Override
	public ResRegFromActivity getCoupon(String userId, String shareKey) {
		ResRegFromActivity resRegFromActivity = new ResRegFromActivity();

		// 验证sharekey是否存在（用户发起活动的唯一标识asId）
		ActivityShare activityShare = this.baseDaoX.getById(shareKey, ActivityShare.class);
		if (activityShare == null) {
			throw new BussinessException(BizExpEnum.SHARE_KEY_ERROR);
		}

		// 判断是否参加过这次活动
		boolean haveJoinTangshanKaiCheng = this.activityShareDao.haveJoinTangshanKaiCheng(userId);

		// 如果没有参加过活动
		if (!haveJoinTangshanKaiCheng) {

			// 添加被邀请人的记录
			this.activityShareDao.addInviteRecord(shareKey, userId);

			// 给该发起活动的人添加一次邀请人数
			this.activityShareDao.addActAnsInviteNum(shareKey);

			resRegFromActivity.setUserType(2);// 2是提示成功领取到优惠券
			return resRegFromActivity;

		} else {
			resRegFromActivity.setUserType(3);// 3是提示用户重复领取，不能领取
			return resRegFromActivity;
		}
	}
}
